﻿using System.Text.RegularExpressions;

namespace BoldBrick.OneIntranet.HR.DataObjects.Lists.WorkflowHistoryListData
{
	/// <summary>
	/// This class represents value in "Data" field of workflow history list
	/// </summary>
	public class WorkflowHistoryListDataValue
	{
		public const string WorkflowItemIdKey = "workflowitemid";
		public const string PositionItemIdKey = "positionitemid";
		public const string WorkflowStepIdKey = "workflowstepid";

		public int WorkflowItemId { get; set; }

		public int PositionItemId { get; set; }

		public int? WorkflowStepId { get; set; }

		public WorkflowHistoryListDataValue()
		{
			
		}

		public WorkflowHistoryListDataValue(string data)
		{
			if (data == null)
				return;

			int? workflowItemId = GetValue(data, WorkflowItemIdKey);
			if (workflowItemId.HasValue)
			{
				this.WorkflowItemId = workflowItemId.Value;
			}

			int? positionItemId = GetValue(data, PositionItemIdKey);
			if (positionItemId.HasValue)
			{
				this.PositionItemId = positionItemId.Value;
			}

			this.WorkflowStepId = GetValue(data, WorkflowStepIdKey);
		}

		private static int? GetValue(string data, string key)
		{
			string pattern = string.Format("{0}=(.*?);", key);
			Match match = Regex.Match(data, pattern);
			if (!match.Success)
				return null;

			int number;
			if (int.TryParse(match.Groups[1].Value, out number))
			{
				return number;
			}

			return null;
		}

		public override string ToString()
		{
			return string.Format("{0}{1}{2}",
				GetParameter(WorkflowItemIdKey, this.WorkflowItemId),
				GetParameter(PositionItemIdKey, this.PositionItemId),
				GetParameter(WorkflowStepIdKey, this.WorkflowStepId)
				);
		}

		public static string GetParameter(string key, int? value)
		{
			if (value == null)
				return null;
			
			return string.Format("{0}={1};", key, value);
		}
	}
}
